#include "RegisterModule.h"

#include "rutil/DnsUtil.hxx"
#include "resip/dum/MasterProfile.hxx"

#include <iostream>

using namespace resip;
using namespace std;

RegisterModule::RegisterModule(DialogUsageManager* dum, SipStack* stack) : m_registerHandler(0), m_dialogUsageManager(dum), m_stack(stack)
{
	initialize();
}

RegisterModule::~RegisterModule()
{
	cleanup();
}

void RegisterModule::initialize()
{
	// Initialize RegisterHandler

	initializeHandler();

	// Initialize Users information

	initializeUsers();
}

void RegisterModule::initializeHandler()
{
	m_registerHandler = new RegisterHandler();
	m_dialogUsageManager->setClientRegistrationHandler( m_registerHandler );
}

void RegisterModule::initializeUsers()
{
	m_baseAor.uri().port() = BASEPORT;
	m_baseAor.uri().host() = DnsUtil::getLocalIpAddress();

	m_destAor.uri().port() = DESTPORT;
}

void RegisterModule::cleanup()
{
	if( m_registerHandler )
	{
		delete m_registerHandler;
		m_registerHandler = 0;
	}
}

void RegisterModule::setScheme(string scheme)
{
	m_baseAor.uri().scheme() = scheme.c_str();
	m_destAor.uri().scheme() = scheme.c_str();
}

void RegisterModule::setBaseUser(string user)
{
	m_baseAor.uri().user() = user.c_str();
}

void RegisterModule::setDestUser(string user)
{
	m_destAor.uri().user() = user.c_str();
}

void RegisterModule::setDestHost(string uri)
{
	m_destAor.uri().host() = uri.c_str();
}

void RegisterModule::setDestPassword(string password)
{
	m_password = password;
}

void RegisterModule::sendRegisterMessage()
{
	// Do necessary configuration

	m_dialogUsageManager->getMasterProfile()->setDefaultFrom(m_baseAor);
	m_dialogUsageManager->getMasterProfile()-> setDigestCredential(m_destAor.uri().host(),
		m_destAor.uri().user(), Data(m_password) );

	// Make REGISTER message

	SharedPtr<SipMessage> request = m_dialogUsageManager->makeRegistration(m_destAor);
	m_dialogUsageManager->send(request);

	// Wait for response

	waitForResponse();
}

void RegisterModule::waitForResponse()
{
	while( !m_registerHandler->isDone() )
	{
		FdSet fdset;
		m_stack->buildFdSet(fdset);
		fdset.selectMilliSeconds(SELECT_TIME);
		m_stack->process(fdset);

		while( m_dialogUsageManager->process() )
			;
	}
}